import BaseVenueProcessor from './BaseVenueProcessor.js';
import { getQuanAiLiWanVenueSettings } from '../request.js';

/**
 * 全爱网球(荔湾店)场地数据处理器
 */
export class QuanAiLiWanProcessor extends BaseVenueProcessor {
  constructor() {
    super();
    this.venueName = '全爱网球(荔湾店)';
    this.timeSlots = [
      '06:00-07:00', '07:00-08:00', '08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00',
      '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00', '17:00-18:00',
      '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00', '22:00-23:00', '23:00-24:00'
    ];
  }

  /**
   * 获取全爱网球(荔湾店)场地预约设置
   * @param {Object} params - 查询参数 { startDate, endDate }
   * @returns {Promise} 请求Promise
   */
  async getVenueSettings(params = {}) {
    // 设置默认参数
    const today = new Date();
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
    
    // 格式化为指定格式：Wed Oct 15 2025 00:00:00 GMT+0800 (中国标准时间)
    const formatDate = (date) => {
      return date.toString();
    };
    
    const defaultParams = {
      startDate: formatDate(today),
      endDate: formatDate(tomorrow)
    };
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getQuanAiLiWanVenueSettings(requestData);
  }

  /**
   * 验证数据是否有效
   * @param {Object} data - 原始场地数据
   * @returns {boolean} 数据是否有效
   */
   validateData(data) {
    return data && 
           Array.isArray(data) &&
           data.length > 0 &&
           data[0] &&
           data[0].data &&
           data[0].data.data &&
           Array.isArray(data[0].data.data.courtList);
  }
  
  /**
   * 将场地数据按场地名称分组
   * @param {Array} data - 原始场地数据数组
   * @returns {Map} 按场地名称分组的数据
   */
  groupVenues(data) {
    const venueMap = new Map();
    
    // 遍历所有API响应数据
    data.forEach(apiResponse => {
      if (apiResponse && apiResponse.data && apiResponse.data.data && apiResponse.data.data.courtList) {
        // 根据courtList数据创建场地分组
        apiResponse.data.data.courtList.forEach(court => {
          const venueName = court.subClassroomName || `${court.number}号场`;
          if (!venueMap.has(venueName)) {
            venueMap.set(venueName, {
              name: venueName,
              dataSource: this.venueName,
              timeSlots: [],
              courtId: court.number,
              maxPeople: 4, // 网球场默认4人
              pic: '', // 可以后续添加图片
              subClassroomNumber: court.number
            });
          }
        });
      }
    });
    
    return venueMap;
  }

  /**
   * 处理时间段数据
   * @param {Map} venueMap - 按场地分组的数据
   * @param {Array} data - 原始数据数组
   */
  processTimeSlots(venueMap, data) {
    // 定义时间段，从06:00到24:00，每小时一个时间段
    const timeSlots = [];
    for (let hour = 6; hour <= 23; hour++) {
      const startTime = `${hour.toString().padStart(2, '0')}:00`;
      const endTime = `${(hour + 1).toString().padStart(2, '0')}:00`;
      timeSlots.push({
        time: `${startTime}-${endTime}`,
        startHour: hour,
        endHour: hour + 1
      });
    }

    // 遍历所有API响应数据
    data.forEach(apiResponse => {
      if (apiResponse && apiResponse.data && apiResponse.data.data && apiResponse.data.data.courtList) {
        // 遍历每个场地
        apiResponse.data.data.courtList.forEach(court => {
          const venueName = court.subClassroomName || `${court.number}号场`;
          const venue = venueMap.get(venueName);
          
          if (venue && court.list && Array.isArray(court.list)) {
            // 为每个时间段添加时间槽信息
            timeSlots.forEach((timeSlot, index) => {
              // 获取对应索引的API数据，如果没有则设为不可用
              const apiSlot = court.list[index];
              
              let isFree = false;
              let price = 0;
              let remark = '';
              
              if (apiSlot) {
                // status为0表示可预约
                isFree = apiSlot.status === 0;
                // 价格除以100转换为元
                price = apiSlot.price / 100;
                remark = apiSlot.isMakeAppointment ? '需预约' : '';
              }
              
              const beginDatetime = `${this.selectedDate} ${timeSlot.time.split('-')[0]}`;
              const endDatetime = `${this.selectedDate} ${timeSlot.time.split('-')[1]}`;
              
              venue.timeSlots.push({
                time: timeSlot.time,
                isFree: isFree,
                price: price,
                beginDatetime: beginDatetime,
                endDatetime: endDatetime,
                resourceId: apiSlot ? apiSlot.id : null,
                remark: remark
              });
            });
          }
        });
      }
    });
  }

  /**
   * 将分组后的场地数据转换为列表格式
   * @param {Map} venueMap - 按场地分组的数据
   * @returns {Array} 场地列表
   */
  convertToVenueList(venueMap) {
    const venues = [];
    
    venueMap.forEach((venue, venueName) => {
      // 只添加有时间槽的场地
      if (venue.timeSlots.length > 0) {
        venues.push({
          name: venueName,
          dataSource: venue.dataSource,
          timeSlots: venue.timeSlots,
          courtId: venue.courtId,
          maxPeople: venue.maxPeople,
          pic: venue.pic,
          subClassroomNumber: venue.subClassroomNumber
        });
      }
    });
    
    return venues;
  }

  /**
   * 处理场地数据
   * @param {Array} data - 原始场地数据数组
   * @param {Date} selectedDate - 选择的日期
   * @returns {Array} 处理后的场地列表
   */
 process(data, selectedDate) {
    this.selectedDate = selectedDate;
    
    if (!this.validateData(data)) {
      console.warn('全爱网球(荔湾店)数据验证失败:', data);
      return [];
    }

    const venueMap = this.groupVenues(data);
    this.processTimeSlots(venueMap, data);
    console.log("全爱网球(荔湾店) venueMap", data);
    
    return this.convertToVenueList(venueMap);
  }
}

export default QuanAiLiWanProcessor;